/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 17:59:28
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-03-20 01:02:11
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import debounce from 'lodash/debounce';
import { routerRedux } from 'dva/router';
import {
  Alert,
  AutoComplete,
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  List,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Tag,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
  Spin,
} from 'antd';
import SimpleTable from 'components/SimpleTable';
import NestedTable from 'components/NestedTable';
import StandardTable from 'components/StandardTable';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './enterprise.less';

const FormItem = Form.Item;

const { Option } = Select;

const { RangePicker } = DatePicker;

const CreateForm = Form.create()(prop => {
  const { state, form, props, handleHide } = prop;
  const { modalVisible, orderId } = state;
  const { getFieldDecorator, validateFields } = form;
  const { dispatch } = props;

  const handleOk = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        ...fieldsValue,
      };

      dispatch({
        type: 'orderDetail/orderCancel',
        payload: { orderId, cancelRemark: params.cancelRemark },
        callback: res => {
          if (res.success) {
            message.success('取消成功');
            dispatch(routerRedux.push('/Order/order-list'));
          } else {
            message.info(res.errorDesc);
          }
        },
      });
    });
  };

  return (
    <Modal
      title="取消备注"
      visible={modalVisible}
      onOk={() => handleOk()}
      onCancel={() => handleHide()}
      className=""
      okText="确认取消"
      width="300px"
      destroyOnClose
    >
      <Form layout="inline">
        <Row gutter={{ lg: 24 }}>
          <Col md={24} sm={24}>
            <FormItem label="取消备注">
              {getFieldDecorator('cancelRemark', {})(
                <Input.TextArea style={{ width: '240px' }} placeholder="请输入取消备注" />
              )}
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

@connect(({ orderDetail, dict, institutionList, loading }) => ({
  orderDetail,
  dict,
  institutionList,
  loading: loading.models.companyStorePage,
}))
@Form.create()
export default class TableList extends PureComponent {
  constructor(props) {
    super(props);
  }

  state = {
    expandedRowKeys: [],
    selectedRows: [],
    selectedRowsKeys: [],
    selectedExpandedRows: [],
    orderId: '',
    contractId: '',
    employeeId: '',
    packageId: '',
    cityId: '',
    institutionId: '',
    provinceId: '',
    storeUnavailableTimeList: '',
    modalVisible: false,
  };

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;
    if (query) {
      const { id, packageId, employeeId } = query;
      dispatch({
        type: 'orderDetail/orderDetail',
        payload: { orderId: id },
        callback: res => {
          const {
            data: { extraItemList },
          } = res;
          if (extraItemList instanceof Array) {
            const newList = extraItemList.map(v => {
              if (v.extraItemDetailList.length) {
                return v.id;
              }
            });
            this.setState({
              expandedRowKeys: newList,
            });
          }
        },
      });

      this.setState({ packageId, employeeId });

      dispatch({
        type: 'dict/dictOrderPackageStoreList',
        payload: { packageId, employeeId },
      });

      this.setState({
        orderId: id,
      });
    }

    // 查询省份
    dispatch({
      type: 'dict/dictProvinceList',
      payload: {},
    });

    // 适用机构
    dispatch({
      type: 'institutionList/dictInstitutionList',
      payload: {},
    });
  }

  handleEdit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { orderId } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        ...fieldsValue,
        appointmentDate: fieldsValue.appointmentDate
          ? moment(fieldsValue.appointmentDate).format('YYYY-MM-DD')
          : '',
      };
      params.orderId = orderId;
      dispatch({
        type: 'orderDetail/orderEdit',
        payload: params,
        callback: res => {
          if (res.success) {
            message.success('修改成功');
            dispatch(routerRedux.push('/Order/order-list'));
          } else {
            message.info(res.errorDesc);
          }
        },
      });
    });
  };

  handleSubmit = () => {
    const { orderId } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'orderDetail/orderEdit',
      payload: { orderId },
      callback: res => {
        if (res.success) {
          message.success('修改成功');
        } else {
          message.info(res.errorDesc);
        }
      },
    });
  };

  handleSuccess = () => {
    const { orderId } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'orderDetail/orderCommit',
      payload: { orderId },
      callback: res => {
        if (res.success) {
          message.success('预约成功');
          dispatch(routerRedux.push('/Order/order-list'));
        } else {
          message.info(res.errorDesc);
        }
      },
    });
  };

  handleCancel = () => {
    const { orderId } = this.state;
    const { dispatch } = this.props;

    this.setState({
      modalVisible: true,
    });
  };

  handleHide = () => {
    this.setState({
      modalVisible: false,
    });
  };

  handleBack = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/Order/order-list'));
  };

  handleExpandedSelect = rows => {
    const {
      extraItemList: { extraItemList },
    } = this.props;

    this.setState({
      selectedExpandedRows: rows,
    });
  };

  expandedRowRender = record => {
    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        align: 'center',
      },
      {
        title: '描述',
        dataIndex: 'description',
        align: 'center',
      },
      {
        title: '价格',
        dataIndex: 'price',
        align: 'center',
      },
    ];

    const extraItemDetailList = record.extraItemDetailList ? record.extraItemDetailList : [];
    const { loading } = this.props;
    const { selectedExpandedRows } = this.state;

    return (
      <StandardTable
        selectedRows=""
        onSelectRow={false}
        style={{ background: '#fff' }}
        loading={loading}
        rowKey="key"
        data={{ list: extraItemDetailList, pagination: {} }}
        columns={columns}
        onChange={this.handleStandardTableChange}
      />
    );
  };

  handleOnExpand = (expand, record) => {
    // const { expandedRowKeys } = this.state;
    // if (!expand) {
    //   const newKeys = expandedRowKeys.filter(key => {
    //     return key !== record.key;
    //   });
    //   this.setState({ expandedRowKeys: newKeys });
    //   return;
    // }
    // this.setState({ expandedRowKeys: [...expandedRowKeys, record.key] });
  };

  handleMainSelect = rows => {
    const { selectedExpandedRows } = this.state;
    const newlist = selectedExpandedRows.map(v => {
      return v.id;
    });
    this.setState({
      selectedRows: rows,
      selectedRowsKeys: newlist,
    });
  };

  orderStatus = x => {
    switch (x) {
      case '1':
        return '下单';
      case '2':
        return '修改';
      case '3':
        return '预约成功';
      case '4':
        return '生成体检报告';
      case '5':
        return '已取消';
      default:
        return '';
    }
  };

  payStatus = x => {
    switch (x) {
      case '0':
        return '未支付';
      case '1':
        return '支付成功';
      case '2':
        return '支付失败';
      default:
        return '';
    }
  };

  // 门店render
  renderOptionsStoreId = () => {
    const {
      dict: { dictOrderPackageStoreList },
    } = this.props;
    const options = dictOrderPackageStoreList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    return options;
  };

  renderOptionsC = () => {
    const {
      dict: { cityList },
    } = this.props;
    const options = cityList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    return options;
  };

  renderOptionsI = () => {
    const {
      institutionList: { dictInstitutionList },
    } = this.props;
    const options = dictInstitutionList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    return options;
  };

  renderOptionsP = () => {
    const {
      dict: { provinceList },
    } = this.props;
    const options = provinceList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    return options;
  };

  onChangeP = v => {
    // 查询城市
    const { dispatch } = this.props;
    const { cityId, institutionId } = this.state;
    this.setState({
      provinceId: v,
    });
    dispatch({
      type: 'dict/dictCityList',
      payload: { provinceId: v, cityId, institutionId },
    });
  };

  onChangeC = v => {
    // 查询门店
    const { dispatch } = this.props;
    const { provinceId, institutionId } = this.state;
    this.setState({
      cityId: v,
    });
    // 查询门店
    dispatch({
      type: 'dict/dictStoreList',
      payload: { cityId: v, institutionId, provinceId },
    });
  };

  onChangeI = v => {
    // 查询门店
    const { dispatch } = this.props;
    const { cityId, provinceId } = this.state;

    this.setState({
      institutionId: v,
    });
    // 查询门店
    dispatch({
      type: 'dict/dictStoreList',
      payload: { institutionId: v, cityId, provinceId },
    });
  };

  focusStore = () => {
    const { dispatch } = this.props;
    const { contractId, employeeId, packageId, cityId, institutionId, provinceId } = this.state;
    dispatch({
      type: 'dict/dictOrderPackageStoreList',
      payload: { packageId, contractId, employeeId, cityId, institutionId, provinceId },
    });
  };

  onSelectStoreId = v => {
    const {
      dispatch,
      dict: { dictOrderPackageStoreList },
    } = this.props;
    const { contractId } = this.state;

    const newlist = dictOrderPackageStoreList.filter(item => {
      return item.id == v;
    });

    this.setState({
      storeUnavailableTimeList: newlist[0]?.storeUnavailableTimeList,
    });
  };

  renderList = l => {
    let list = [];
    if (l instanceof Array) {
      l.map(v => {
        list.push(
          <div className={styles.logListContainer}>
            <span>{v.createTime}</span>
            <span>{v.content}</span>
          </div>
        );
      });
    }
    return list;
  };

  render() {
    const {
      loading,
      form,
      orderDetail: { info },
    } = this.props;

    const { selectedRows, expandedRowKeys, storeUnavailableTimeList } = this.state;
    const { getFieldDecorator } = form;
    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
      },
      {
        title: '描述',
        dataIndex: 'description',
      },
      {
        title: '价格',
        dataIndex: 'price',
      },
      {
        title: '详情',
        dataIndex: 'url',
        render: (v, r) => (
          <a href={v} target="_blank">
            点击查看
          </a>
        ),
      },
    ];
    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <Alert message="基本信息" type="info" />
          <Form layout="inline">
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="企业名称">
                  <span>{info.companyName}</span>
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="员工">
                  <span>{info.employeeName}</span>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="证件类型">
                  <span>{info.employeeIdentityType == '1' ? '身份证' : '护照'}</span>
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="证件号">
                  <span>{info.employeeIdentityNo}</span>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="手机">
                  <span>{info.employeeMobile}</span>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="订单时间">
                  <span>{info.createTime}</span>
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="修改时间">
                  <span>{info.updateTime}</span>
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={12} sm={24}>
                <FormItem label="家属姓名">
                  <span>{info.familyName}</span>
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="家属证件">
                  <span>{info.familyIdentityNo}</span>
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={12} sm={24}>
                <FormItem label="订单金额">
                  <span>{info.totalAmount} 元</span>
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="实付金额">
                  <span>{info.actualAmount} 元</span>
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={12} sm={24}>
                <FormItem label="缴费状态">
                  <span>{this.payStatus(info.payStatus)}</span>
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="订单状态">
                  <span>{this.orderStatus(info.orderStatus)}</span>
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ lg: 24 }}>
              <Col md={6} sm={24}>
                <FormItem>
                  <span>选择省份：</span>
                  <Select
                    showSearch
                    allowClear={true}
                    onSelect={this.onChangeP}
                    placeholder="请选择"
                    style={{ width: 120 }}
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {this.renderOptionsP()}
                  </Select>
                </FormItem>
              </Col>
              <Col md={6} sm={24}>
                <FormItem>
                  <span>选择城市：</span>
                  <Select
                    showSearch
                    allowClear
                    onSelect={this.onChangeC}
                    placeholder="请选择"
                    style={{ width: 120 }}
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {this.renderOptionsC()}
                  </Select>
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem>
                  <span>选择机构：</span>
                  <Select
                    showSearch
                    allowClear
                    onSelect={this.onChangeI}
                    placeholder="请选择"
                    style={{ width: 160 }}
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {this.renderOptionsI()}
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="门店">
                  {getFieldDecorator('storeId', {
                    initialValue: info?.storeId,
                  })(
                    <Select
                      onFocus={this.focusStore}
                      placeholder="请选择门店"
                      style={{ width: 300 }}
                      onSelect={this.onSelectStoreId}
                    >
                      {this.renderOptionsStoreId()}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="预约时间">
                  {getFieldDecorator('appointmentDate', {
                    initialValue: moment(info?.appointmentDate),
                  })(<DatePicker format="YYYY-MM-DD" tyle={{ width: 150 }} />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                &nbsp;
              </Col>
              <Col md={12} sm={24}>
                {storeUnavailableTimeList
                  ? storeUnavailableTimeList.map(v => (
                      <p style={{ color: 'red' }}>
                        {v.beginDate} ~ {v.endDate}
                      </p>
                    ))
                  : ''}
              </Col>
            </Row>
            <Row gutter={{ lg: 24 }}>
              <Col md={6} sm={24}>
                <FormItem label="付款状态">
                  {getFieldDecorator('payStatus', {
                    initialValue: info?.payStatus,
                    rules: [{ required: true, message: '请选择付款状态' }],
                  })(
                    <Select
                      disabled
                      onSelect={this.onChangeP}
                      placeholder="请选择"
                      style={{ width: 120 }}
                    >
                      <Option key="0" value="0">
                        未支付
                      </Option>
                      <Option key="1" value="1">
                        支付成功
                      </Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              {info.ifAcceptRadio ? (
                <Col md={6} sm={24}>
                  <FormItem label="是否做放射性检查项目">
                    <span>{info.ifAcceptRadio === '1' ? '是' : '否'}</span>
                  </FormItem>
                </Col>
              ) : (
                ''
              )}
            </Row>
            <Row gutter={{ lg: 24 }}>
              <Col md={12} sm={24}>
                <FormItem label="付款信息备注">
                  {getFieldDecorator('payRemark', {
                    initialValue: info?.payRemark,
                  })(<Input.TextArea readOnly style={{ width: '240px' }} />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
          <Alert message="套餐信息" type="info" style={{ marginBottom: 10, marginTop: 10 }} />
          <Form layout="inline">
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="套餐名称">
                  <span>{info.packageName}</span>
                </FormItem>
              </Col>
            </Row>
          </Form>

          <SimpleTable
            selectedRows={false}
            onSelectRow={false}
            loading={loading}
            data={{ list: info.extraItemList, pagination: false }}
            columns={columns}
            onChange=""
            rowKey="id"
          />

          <Alert message="套餐服务" type="info" style={{ marginBottom: 10, marginTop: 10 }} />
          {info.serviceList ? (
            info.serviceList.map(v => {
              return (
                <List
                  header={
                    <div>
                      {v.name} ({v.description})
                    </div>
                  }
                  bordered
                  dataSource={v.serviceDetailList}
                  renderItem={item => (
                    <List.Item
                      actions={[
                        <a href={item.attachmentUrl} target="_blank">
                          查看详情
                        </a>,
                      ]}
                    >
                      {item.name}
                    </List.Item>
                  )}
                  className={styles.listContainer}
                />
              );
            })
          ) : (
            <p>暂无</p>
          )}

          <Alert message="操作记录" type="info" style={{ marginBottom: 10, marginTop: 10 }} />
          {this.renderList(info.logList)}
        </Card>
        <div style={{ textAlign: 'center', marginBottom: '20px' }}>
          {info.orderStatus === '5' || info.orderStatus === '4' ? (
            ''
          ) : info.orderStatus === '3' ? (
            <span>
              <Button type="primary" style={{ marginRight: 20 }} onClick={this.handleEdit}>
                修改订单
              </Button>
              <Button type="primary" style={{ marginRight: 20 }} onClick={this.handleSuccess}>
                预约成功
              </Button>
              <Button type="primary" onClick={this.handleCancel}>
                取消订单
              </Button>
            </span>
          ) : (
            <span>
              <Button type="primary" style={{ marginRight: 20 }} onClick={this.handleEdit}>
                修改订单
              </Button>
              <Button type="primary" style={{ marginRight: 20 }} onClick={this.handleSuccess}>
                预约成功
              </Button>
              <Button type="primary" onClick={this.handleCancel}>
                取消订单
              </Button>
            </span>
          )}
          <Button style={{ marginLeft: 20 }} type="" onClick={this.handleBack}>
            返回
          </Button>
        </div>
        <CreateForm {...this} />
      </PageHeaderLayout>
    );
  }
}
